package leetcode;

import org.junit.Test;

/**
 * @author: feiwang_6
 * @create: 2020/4/18 17:19
 * @description:
 */
public class IntToRoman {
    @Test
    public void testMath(){
        System.out.println(intToRoman(1994));
        System.out.println(romanToInt("XXVI"));
        //System.out.println(myRomanToInt("XXVI"));
        System.out.println("1123".charAt(2));
    }
    public String intToRoman(int tag){
        int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        int index = 0;
        StringBuffer buffer = new StringBuffer();
        while (index < nums.length){
            if(tag >= nums[index]){
                buffer.append(romans[index]);
                tag -= nums[index];
                continue;
            }
            index++;
        }
        return buffer.toString();
    }
    
    public int myRomanToInt(String s){
        int sum =0, num;
        int preNum = getValue(s.charAt(0));
        for(int i = 1; i < s.length(); i++){
            num = getValue(s.charAt(i));
            if(preNum < num){
                sum -= preNum;
            }else {
                sum += preNum;
            }
            preNum = num;
        }
        return sum + preNum;
    }
    
    
    public int romanToInt(String s){
        int sum = 0;
        int preNum = getValue(s.charAt(0));
        for(int i = 1; i < s.length(); i ++) {
            int num = getValue(s.charAt(i));
            if(preNum < num) {
                sum -= preNum;
            } else {
                sum += preNum;
            }
            preNum = num;
        }
        sum += preNum;
        return sum;
    }
    
    private int getValue(char r){
        switch (r){
            case 'I' : return 1;
            case 'V' : return 5;
            case 'X' : return 10;
            case 'L' : return 50;
            case 'C' : return 100;
            case 'D' : return 500;
            case 'M' : return 1000;
            default: return 0;
        }
    }
}
